<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <div class="text-right">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <!-- <el-button @click="handleReset(form)">重置</el-button> -->
        <el-button type="primary" plain @click="handleReturn">返回</el-button>
      </div>
    </FixedOperation>
    <div class="app-container form-box">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="150px"
      >
        <el-collapse v-model="activeNames">
          <!-- 基本信息 -->
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="基本信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="订单标题" prop="title">
                  <el-input
                    v-model="formData.title"
                    placeholder="请输入订单标题"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.number">
                <el-form-item label="订单编号" prop="number">
                  <el-input
                    disabled
                    v-model="formData.number"
                    placeholder="请输入订单编号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="7" style="padding-right: 0px">
                <el-form-item label="产品属性" prop="proProperty">
                  <el-select
                    class="w-full"
                    v-model="formData.proProperty"
                    placeholder="请选择产品属性"
                  >
                    <el-option
                      v-for="item in product_property"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5" style="padding-left: 0px">
                <el-form-item label="产品类型" prop="proType" label-width="0">
                  <template #label="{ label }">
                    <div class="hidden">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    v-model="formData.proType"
                    placeholder="请选择产品类型"
                  >
                    <el-option
                      v-for="item in order_pro_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="属性" prop="property">
                  <el-radio-group v-model="formData.property">
                    <el-radio
                      v-for="item in order_property"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="订单金额" prop="price">
                  <el-input
                    v-model="formData.price"
                    placeholder="请填写订单金额"
                    ><template v-slot:append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否收付货款" prop="isPayment">
                  <el-radio-group v-model="formData.isPayment">
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierId">
                  <el-select
                    class="w-full"
                    v-model="formData.supplierId"
                    placeholder="请选择供应商"
                    @focus="selectCustomerFn('supplierId')"
                  >
                    <el-option
                      v-for="item in supplierOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <!-- <el-select
                    v-model="formData.supplierId"
                    placeholder="请输入供应商名称检索供应商"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    @change="chagneSupplier"
                    :remote-method="querySupplier"
                    :loading="loadingSelect"
                    no-data-text="未查询到供应商"
                  >
                    <el-option
                      v-for="item in supplierOptions"
                      :key="item.id"
                      :label="item.supplierName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.supplierName }}</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务分类" prop="bizType">
                  <el-select
                    class="w-full"
                    v-model="formData.bizType"
                    placeholder="请选择业务分类"
                  >
                    <el-option
                      v-for="item in inner_biz_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商税号" prop="customerTaxcode">
                  <el-input
                    :disabled="true"
                    v-model="formData.customerTaxcode"
                    placeholder="根据“供应商”的选择自动带出"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货日期" prop="deliveryDate">
                  <el-date-picker
                    style="width: 100%"
                    v-model="formData.deliveryDate"
                    type="date"
                    placeholder="交货日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关联项目" prop="projectName">
                  <el-input
                    @click="selectPro"
                    placeholder="请选择关联项目"
                    v-model="formData.projectName"
                    clearable
                    :suffix-icon="'el-icon-search'"
                    @clear="clearPro"
                  ></el-input>
                  <!-- <el-select
                    v-model="formData.projectId"
                    placeholder="请输入项目名称检索项目"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    :remote-method="queryProject"
                    @change="changeProject"
                    :loading="loadingSelect"
                    no-data-text="未查询到项目"
                  >
                    <el-option
                      v-for="item in projectOptions"
                      :key="item.projectId"
                      :label="item.proName"
                      :value="item.projectId"
                    >
                      <div>
                        <span>{{ item.proName }}</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货地点" prop="transportPlace">
                  <el-input
                    v-model="formData.transportPlace"
                    placeholder="请输入交货地点"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目编码" prop="projectNumber">
                  <el-input
                    disabled
                    v-model="formData.projectNumber"
                    placeholder="请输入项目编码"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="内部接收方" prop="customerId">
                  <el-select
                    class="w-full"
                    v-model="formData.customerId"
                    placeholder="请选择内部接收方"
                  >
                    <el-option
                      v-for="item in bidding_unit"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库" prop="warehouse">
                  <el-select
                    v-model="formData.warehouse"
                    placeholder="请输入仓库名称检索仓库"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    :remote-method="
                      val => queryWhsLimitEnt(val, { unit: formData.deptId })
                    "
                    :loading="loadingSelect"
                    no-data-text="未查询到仓库"
                  >
                    <el-option
                      v-for="item in whsOptLimitEnt"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                  <!-- <el-select
                    class="w-full"
                    v-model="formData.warehouse"
                    placeholder="请选择仓库"
                  >
                    <el-option
                      v-for="item in warehouse_info"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货人" prop="receiveName">
                  <el-input
                    v-model="formData.receiveName"
                    placeholder="请输入收货人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运输方式" prop="transportType">
                  <el-select
                    class="w-full"
                    v-model="formData.transportType"
                    placeholder="请选择运输方式"
                  >
                    <el-option
                      v-for="item in order_transport_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货地址" prop="receivePlace">
                  <el-input
                    v-model="formData.receivePlace"
                    placeholder="请输入收货地址"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运费承担" prop="transportMan">
                  <el-select
                    class="w-full"
                    v-model="formData.transportMan"
                    placeholder="请选择运费承担"
                  >
                    <el-option
                      v-for="item in order_transport_man"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货人电话" prop="receivePhone">
                  <el-input
                    v-model="formData.receivePhone"
                    placeholder="请输入收货人电话"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属公司 " prop="deptId">
                  <el-tree-select
                    class="w-full"
                    v-model="formData.deptId"
                    placeholder="请选择所属公司"
                    default-expand-all
                    :data="companyOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否开具发票" prop="isInvoice">
                  <el-radio-group v-model="formData.isInvoice">
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createDept">
                <el-form-item label="申请部门" prop="createDept">
                  <el-tree-select
                    class="w-full"
                    disabled
                    v-model="formData.createDept"
                    placeholder="系统自动带入申请部门"
                    :data="departmentOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发票类型" prop="invoiceType">
                  <el-select
                    class="w-full"
                    v-model="formData.invoiceType"
                    placeholder="请选择发票类型"
                  >
                    <el-option
                      v-for="item in invoice_manage_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createTime">
                <el-form-item label="申请日期" prop="createTime">
                  <el-date-picker
                    disabled
                    style="width: 100%"
                    v-model="formData.createTime"
                    type="date"
                    placeholder="申请日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createName">
                <el-form-item label=" 申请人" prop="createName">
                  <el-input
                    disabled
                    v-model="formData.createName"
                    placeholder="系统自动带入新建的用户名称"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 产品信息 -->
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="产品信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <avue-crud
              ref="crudProduct"
              :option="crudOptionProduct"
              :data="formData.productInfoList"
            >
              <template #menu="{ row, index }">
                <el-button
                  plain
                  icon="Delete"
                  link
                  @click="delRowProduct(row, index)"
                  >删除</el-button
                >
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
              <template #footer>
                <el-col :span="24" class="py-2 text-right">
                  产品记录数：<span class="text-blue-500"
                    >{{ countCrudData.num }}条</span
                  >
                  产品总数：<span class="text-blue-500">{{
                    countCrudData.total
                  }}</span
                  >个 产品总售价：<span class="text-blue-500"
                    >{{ countCrudData.totalDiscountPrice }}元</span
                  >
                  整单折扣：<span class="text-blue-500"
                    >{{ countCrudData.discount }}%</span
                  >
                  产品总金额：
                  <span class="text-blue-500"
                    >{{ countCrudData.totalPrice }}元</span
                  >
                </el-col>
                <el-button
                  plain
                  type="primary"
                  icon="Plus"
                  class="w-full"
                  @click="addProduct"
                  >添加产品</el-button
                >
              </template>
            </avue-crud>
          </el-collapse-item>
          <!-- 付款计划 -->
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="付款计划"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="24">
                <avue-crud
                  ref="crudRepayment"
                  :option="crudOptionRepayment"
                  :data="formData.repaymentPlanList"
                >
                  <template #menu-left> </template>
                  <template #period="{ row }">
                    <span>{{ rowIndex(row) }}</span>
                  </template>
                  <template #bankCard-form="{ row }">
                    <el-select
                      class="w-full"
                      v-model="row.bankCard"
                      placeholder="请选择收款账号"
                    >
                      <el-option
                        v-for="item in order_bank_card"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                        <div class="flex justify-between">
                          <span>{{ item.label }}</span
                          ><span>{{ item.value }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                  <template #menu="{ row, index }">
                    <el-button
                      plain
                      icon="Delete"
                      link
                      @click="delRowRepayment(row, index)"
                      >删除</el-button
                    >
                  </template>
                  <template #empty>
                    <div>暂无数据</div>
                  </template>
                  <template #footer>
                    <el-col :span="24" class="py-2 text-right">
                      总计划期次： {{ repaymentStatisticsData.num }}期
                      总回款占比：{{ repaymentStatisticsData.proportion }}%
                      总回款金额：¥
                      {{ repaymentStatisticsData.totalPrice }}
                    </el-col>
                    <el-button
                      plain
                      type="primary"
                      icon="Plus"
                      class="w-full"
                      @click="addRowRepayment"
                      >添加期次</el-button
                    >
                  </template>
                </avue-crud>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 其他信息 -->
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="其他信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select
                    class="w-full"
                    v-model="formData.status"
                    placeholder="请选择状态"
                  >
                    <el-option
                      v-for="item in order_status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="终止原因" prop="stopReason">
                  <el-input
                    v-model="formData.stopReason"
                    placeholder="填写终止原因"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注信息" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    placeholder="填写备注信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>

    <!-- 物料选择弹窗 -->
    <ProductDialog
      v-model="dialogData.open"
      :dialogData="dialogData"
      @getData="productDialogFn"
    />

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    />

    <!-- 选择项目 -->
    <RelatedProject
      :relatedParams="proParams"
      @closeDialog="closePro"
      @relatedOver="relatedPro"
    />
  </div>
</template>
<script setup name="InnerOrderForm">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  crudOption, // 子表公用配置
  order_status, //订单状态
  yes_or_no, //是否
  pay_type, //付款方式
  settle_type, //结算方式
  invoice_manage_type, //订单发票类型
  measurement_unit, //产品单位
  product_property, //产品属性
  order_transport_type, //订单运输方式
  order_transport_man, //订单运费承担方
  order_pro_type, //订单产品类型
  order_bank_card, //订单收款账号
  inner_biz_type, // 内部交易业务类型
  bidding_unit, //内部单位
  loadingSelect, //远程检索loading
  companyOption, //所属公司
  departmentOption, //部门树结构
  projectOptions, //项目数据
  queryProject, //检索项目
  querySupplier, //检索供应商
  supplierOptions, //供应商数据
  queryWhsLimitEnt, // 检索仓库数据
  whsOptLimitEnt //仓库数据
} from '@/hooks/dict/order'
import { setInnerOrder, getInnerOrder } from '@/api/indentManage/indent'
import { getSupplierInfo } from '@/api/sourceModules/supplier'
import { delRepaymentPlan } from '@/api/repaymentManage/repayment'
import { isMoneyNot, validateLen } from '@/utils/validate'
import { skipToError, getTreeNodeByParam, getPricipalId } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'

const commonStore = useCommonStore()

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy, type } = getCurrentInstance()
const props = defineProps({
  innerOrderId: {
    type: [Number, String],
    require: true
  }
})
const data = reactive({
  formData: {
    isPayment: '0',
    deptId: userStore.userInfo.orgId,
    productInfoList: [],
    repaymentPlanList: [],
    customerType: 'inner', //客户类型 -- 供应商
    status: '1' //状态默认填单
  },
  formRules: {
    title: [
      {
        required: true,
        message: '请输入订单标题',
        trigger: 'blur'
      },
      validateLen(100)
    ],
    number: [
      {
        required: true,
        message: '请输入订单编号',
        trigger: 'blur'
      }
    ],
    proProperty: [
      {
        required: true,
        message: '请选择产品属性',
        trigger: 'change'
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择内部接收方',
        trigger: 'change'
      }
    ],
    isPayment: [
      {
        required: true,
        message: '请选择是否收付货款',
        trigger: 'change'
      }
    ],
    bizType: [
      {
        required: true,
        message: '请选择业务分类',
        trigger: 'change'
      }
    ],
    proType: [
      {
        required: true,
        message: '请选择产品类型',
        trigger: 'change'
      }
    ],
    isInvoice: [
      {
        required: true,
        message: '请选择是否开具发票',
        trigger: 'change'
      }
    ],
    deptId: [
      {
        required: true,
        message: '请选择所属公司',
        trigger: 'change'
      }
    ],
    warehouse: [
      {
        required: true,
        message: '请选择仓库',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入订单金额',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ]
  },
  activeNames: ['1'],
  crudOptionProduct: {
    ...crudOption, // 子表公用配置
    column: [
      {
        label: '产品名称',
        prop: 'name',
        cell: false,
        rules: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '产品编号',
        prop: 'number',
        cell: false
      },
      {
        label: '规格型号',
        prop: 'specification',
        cell: false
      },
      {
        label: '单位',
        prop: 'unit',
        type: 'select',
        dicData: measurement_unit,
        cell: false
      },
      {
        label: '标准单价',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入标准单价',
            trigger: 'blur'
          }
        ],
        cell: false
      },
      {
        label: '实际售价',
        prop: 'actualPrice',
        type: 'number',
        min: 0,
        class: 'w-full',
        controls: false,
        precision: 2,
        rules: [
          {
            required: true,
            message: '请输入实际售价',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        blur: val => {
          const { value, row } = val
          row.discount = row.price == 0 ? 0 : (1 - value / row.price) * 100
          row.totalPrice = (Number(value) * Number(row.num)).toFixed(2)
        },
        cell: true
      },
      {
        label: '折扣(%)',
        prop: 'discount',
        type: 'number',
        min: 0,
        max: 100,
        class: 'w-full',
        controls: false,
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入折扣(%)',
            trigger: 'blur'
          }
        ],
        blur: val => {
          const { value, row } = val
          row.actualPrice = ((1 - value / 100) * row.price).toFixed(2)
        },
        cell: true
      },
      {
        label: '数量',
        prop: 'num',
        type: 'number',
        min: 0,
        class: 'w-full',
        controls: false,
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }
        ],
        blur: val => {
          const { value, row } = val
          row.totalPrice = (Number(value) * Number(row.actualPrice)).toFixed(2)
        },
        cell: true
      },
      {
        label: '总价(元)',
        prop: 'totalPrice',
        cell: false
      },
      {
        label: '赠品',
        prop: 'present',
        // type: 'textarea',
        // maxRows: 1,
        rules: [
          {
            required: false,
            message: '请输入赠品',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '备注',
        prop: 'remark',
        // type: 'textarea',
        // maxRows: 1,
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },
  crudOptionRepayment: {
    ...crudOption, // 子表公用配置
    menuWidth: 80,
    column: [
      {
        label: '期次',
        prop: 'period',
        width: '50',
        rules: [
          {
            required: true,
            message: '期次',
            trigger: 'blur'
          }
        ],
        value: '1',
        cell: false
      },
      {
        label: '计划回款日期',
        prop: 'repaymentPlanDate',
        type: 'date',
        cell: true,
        valueFormat: 'YYYY-MM-DD',
        rules: [
          {
            required: true,
            message: '请输入计划回款日期',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '计划回款占比(%)',
        prop: 'proportion',
        type: 'number',
        min: 0,
        max: 100,
        class: 'w-full',
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入计划回款占比(%)',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '计划回款金额(元)',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入计划回款金额(元)',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        cell: true
      },
      {
        label: '付款方式',
        prop: 'payType',
        type: 'select',
        dicData: pay_type,
        rules: [
          {
            required: true,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '结算方式',
        prop: 'settleType',
        type: 'select',
        dicData: settle_type,
        rules: [
          {
            required: true,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '收款账号',
        prop: 'bankCard',
        cell: true
      },
      {
        label: '备注',
        prop: 'remark',
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },
  countCrudData: {},
  repaymentStatisticsData: {},
  dialogData: {
    open: false
  },
  showTrainingIndustry: '',
  userOption: {}, //人员选择下拉
  customerOption: {}, //客户选择下拉
  dialogParam: {},
  dialogParamA: {}
})
let {
  formData,
  formRules,
  activeNames,
  crudOptionProduct,
  crudOptionRepayment,
  countCrudData,
  repaymentStatisticsData,
  dialogData,
  showTrainingIndustry,
  userOption,
  customerOption,
  dialogParam,
  dialogParamA
} = toRefs(data)

onMounted(() => {
  // 计算产品数据
  countCrudData.value = computed(() => {
    let obj = {
      num: 0,
      total: 0,
      totalDiscountPrice: 0,
      taxRate: 0,
      totalPrice: 0
    }
    if (
      formData.value.productInfoList &&
      formData.value.productInfoList.length > 0
    ) {
      formData.value.productInfoList.forEach(item => {
        obj.total = Number(item.num) + Number(obj.total)
        obj.totalDiscountPrice =
          Number(item.price) * Number(item.num) + Number(obj.totalDiscountPrice)
        obj.totalPrice = (
          Number(item.totalPrice) + Number(obj.totalPrice)
        ).toFixed(2)
        obj.taxRate = (
          (1 - Number(obj.totalPrice) / Number(obj.totalDiscountPrice)) *
          100
        ).toFixed(2)
        //         产品总数：countCrudData.total
        //产品总金额：countCrudData.totalDiscountPrice
        //         整单折扣：countCrudData.discount
        //         产品总金额： countCrudData.totalPrice
      })
      obj.num = formData.value.productInfoList.length
    }
    return obj
  })

  // 计算付款数据
  repaymentStatisticsData.value = computed(() => {
    let obj = {
      num: 0,
      proportion: 0,
      totalPrice: 0
    }
    if (
      formData.value.repaymentPlanList &&
      formData.value.repaymentPlanList.length > 0
    ) {
      formData.value.repaymentPlanList.forEach(item => {
        obj.proportion = Number(item.proportion) + Number(obj.proportion)
        obj.totalPrice = Number(item.price) + Number(obj.totalPrice)
        //         付款占比.proportion
        //         付款金额 totalPrice
      })
      obj.num = formData.value.repaymentPlanList.length
    }
    return obj
  })
})
// onUpdated(() => {
//   if (!formData.value.deptId) {
//     formData.value.deptId = userStore.userInfo.deptId
//     console.log('userStore==>', userStore.userInfo)
//     console.log('formData.value.deptId==>', formData.value.deptId)
//   }
// })
// watch(
//   () => formData.value.supplierId,
//   (val, old) => {
//     chagneSupplier(formData.value.supplierId)
//   },
//   { deep: true }
// )
watch(
  [() => route.query.innerOrderId, () => props.innerOrderId],
  () => {
    if (route.query.innerOrderId && route.name == type.name) {
      console.log('instance.type.name-->', type.name)

      getFormData(route.query.innerOrderId)
    }
    if (props.innerOrderId) {
      console.log('props.innerOrderId==>', props.innerOrderId)
      getFormData(props.innerOrderId)
    }
  },
  {
    immediate: true
  }
)

// 获取表单信息
function getFormData(id) {
  proxy.$modal.loading('加载中')
  getInnerOrder(id).then(async res => {
    let resData = {}
    resData = res.data
    // 供应商
    if (resData.supplierId) {
      supplierOptions.value = [
        {
          supplierName: resData.supplierName, //? resData.supplierName: resData.supplierId,
          id: resData.supplierId //? resData.supplierId : resData.supplierName
        }
      ]
    }
    //项目数据
    if (resData.projectId) {
      projectOptions.value = [
        {
          proName: resData.projectName,
          projectId: resData.projectId
        }
      ]
    }
    // 仓库数据
    if (resData.warehouse) {
      whsOptLimitEnt.value = [
        {
          id: resData.warehouse,
          name: resData.warehouseName
        }
      ]
    }

    resData.productInfoList.forEach((e, i) => {
      if (e.id) {
        resData.productInfoList[i].$cellEdit = true
      }
    })
    resData.repaymentPlanList.forEach((e, i) => {
      if (e.id) {
        resData.repaymentPlanList[i].$cellEdit = true
      }
    })
    formData.value = resData
    proxy.$modal.closeLoading()
  })
}

// 保存
function handleSubmit(e) {
  proxy.$refs.form.validate((valid, msg) => {
    proxy.$refs.crudProduct.validateCellForm().then(err => {
      if (valid && !err) {
        setInnerOrder(formData.value).then(res => {
          // proxy.$modal.msgSuccess(formData.value.id ? '修改成功' : '新增成功')
          // if (!formData.value.id) {
          //   useTagsViewStore().delView(router.currentRoute.value)
          //   router.go(-1)
          // }
          // 保存接口才有
          proxy.useReturn(
            '',
            () => {
              //返回上一步
              handleReturn()
            },
            async () => {
              //继续
            }
          )
          getFormData(res.data.id)
        })
      } else {
        skipToError()
      }
    })
  })
}
function handleReset() {
  proxy.resetForm('form')
}

// 选择供应商时的方法
function chagneSupplier(val) {
  getSupplierInfo(val).then(async res => {
    console.log('客户详情==》', res.data)
    let resData = res.data
    // 供应商税号赋值
    if (resData.bo.systemNumber) {
      formData.value.systemNumber = resData.bo.systemNumber
    }
    // 供应商名称赋值
    if (resData.bo.supplierName) {
      formData.value.supplierName = resData.bo.supplierName
    }
  })
}

// 选择项目时的方法
function changeProject(val) {
  let pro = projectOptions.value.filter(item => {
    return item.projectId == val
  })
  formData.value.projectName = pro[0].proName
  formData.value.projectNumber = pro[0].proNum
}

/**
 * 人员选择
 * @param keyName handleId:经办人  transactionId:业务员
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'transactionId':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择业务员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [formData.value['_' + keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionName = val.labelData.toString()
      formData.value._transactionId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  dialogParamA.value.type = keyName
  dialogParamA.value.tabVal = 'supplier'
  dialogParamA.value.tabShow = false
  dialogParamA.value.title = '供应商选择'
  dialogParamA.value.isDialog = true
  dialogParamA.value.multiple = false
  dialogParamA.value.nodeKey = 'id'
  dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
  dialogParamA.value.defaultCheckedLabel = formData.value['supplierName']
}

// 客户选择选择确定
const selectCustomerData = val => {
  // console.log('val==>', val)
  // formData.value.customerType = val.tabVal
  if (formData.value.supplierId !== val.defaultCheckedKeys.toString()) {
    supplierOptions.value = val.selectData
    // 供应商名称赋值
    formData.value.supplierName = val.labelData.toString()
    // 供应商税号赋值
    if (val.selectData.length > 0) {
      formData.value.systemNumber = val.selectData[0].supplierTaxcode
    } else {
      formData.value.supplierNumber = ''
    }
    // 供应商id赋值
    formData.value.supplierId = val.defaultCheckedKeys
      ? val.defaultCheckedKeys.toString()
      : null
  }
}
// 添加产品
function addProduct() {
  console.log('dialogData.value.open', dialogData.value.open)
  dialogData.value = {
    open: true
  }
}
// 确定添加产品
function productDialogFn(val, tabName) {
  switch (tabName) {
    case 'ProductMange':
      val.forEach(e => {
        formData.value.productInfoList.push({
          ...e,
          ...{
            $cellEdit: true,
            num: 1,
            actualPrice: e.price,
            totalPrice: e.price,
            productId: e.id,
            discount: 0
          }
        })
      })
      break
    case 'ComboMange':
      val.forEach(e => {
        e.productInfoList.forEach(item => {
          formData.value.productInfoList.push({
            ...item,
            ...{
              $cellEdit: true,
              actualPrice: item.price,
              totalPrice: Number(item.price) * Number(item.num),
              discount: 0
            }
          })
        })
      })
      break
  }
  queryWhsLimitEnt('', { unit: formData.value.deptId })
}
// 删除行
function delRowProduct(row, index, done) {
  proxy
    .$confirm('是否删除该产品', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      formData.value.productInfoList.splice(index, 1)
      proxy.$message({
        type: 'success',
        message: '删除成功!'
      })
    })
    .catch(() => {})
}

// 添加付款
function addRowRepayment() {
  formData.value.repaymentPlanList.push({ $cellEdit: true, price: 0 })
  console.log('product==>', formData.value.repaymentPlanList)
}

// 付款计划期次赋值
function rowIndex(row) {
  row.period = row.$index + 1
  return row.$index + 1
}

// 删除付款行
function delRowRepayment(row, index, done) {
  proxy
    .$confirm('是否删除该付款计划', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      if (row.id) {
        delRepaymentPlan(row.id).then(e => {
          formData.value.repaymentPlanList.splice(index, 1)
          proxy.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      } else {
        formData.value.repaymentPlanList.splice(index, 1)
        proxy.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    })
    .catch(() => {})
}

/****    关联项目  开始  ***/
const proParams = ref({
  visible: false,
  businessId: '',
  businessName: '客户名称'
})
// 打开弹窗
function selectPro() {
  // const id = formData.value.customerId
  // if (!id) {
  //   proxy.$modal.msgError('请先选择客户名称')
  //   return false
  // }
  const ids = formData.value.projectId
  proParams.value = {
    visible: true, // 显示dialog
    businessId: '', //id, //客户id
    businessName: '', //formData.value.customerName, //客户名称
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
  // 注意： 如果不需要选客户名称的话，这个businessId，businessName 可以不传
}

// 弹窗确认完成回调
function relatedPro(val) {
  if (val) {
    console.log(val, 'val')
    const name = proParams.value.multiple
      ? val.map(v => v.proName).toString() || ''
      : val.proName

    const ids = proParams.value.multiple
      ? val.map(v => v.projectId) || []
      : val.projectId

    const nums = proParams.value.multiple
      ? val.map(v => v.proNum) || []
      : val.proNum

    formData.value.projectId = ids
    formData.value.projectName = proParams.value.multiple
      ? val.map(v => v.proName)
      : name
    formData.value.projectNumber = nums
  }
  closePro()
}

// 关闭弹窗
function closePro() {
  proParams.value.visible = false
}

// el-input clear函数
function clearPro() {
  formData.value.projectId = null
  formData.value.projectName = null
}
/****    关联项目  end   ***/

// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}
</script>
<style scoped>
.form-box :deep(.w-full) {
  width: 100%;
}
/* .order-form :deep(.avue-crud__menu) {
  border-bottom: 1px solid #eee;
} */
.form-box:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}

:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
